<template>
  <view class="container">
    
    <!-- 注册方式切换 -->
    <view class="tabs">
      <view class="tab" :class="{ active: regType === 'account' }" @click="regType = 'account'">账号注册</view>
      <view class="tab" :class="{ active: regType === 'phone' }" @click="regType = 'phone'">手机注册</view>
    </view>

    <!-- 账号注册表单 -->
    <view v-if="regType === 'account'" class="register-form">
      <input v-model="account.username" placeholder="请输入用户名" class="input" maxlength="20" />
      <input v-model="account.password" placeholder="请输入密码（至少6位，含字母数字）" class="input" type="password" maxlength="20" />
      <input v-model="account.confirmPassword" placeholder="请确认密码" class="input" type="password" maxlength="20" />
      <input v-model="account.nickName" placeholder="请输入昵称" class="input" maxlength="20" />
      <input v-model="account.email" placeholder="请输入邮箱" class="input" type="email" />
      <input v-model="account.phone" placeholder="请输入手机号" class="input" maxlength="11" />
      <picker :value="sexIndexAcc" :range="sexOptions" range-key="label" @change="(e)=>onSexChange(e,'acc')" class="picker">
        <view class="picker-text" :class="{ 'placeholder': sexIndexAcc === -1 }">{{ sexLabelAcc }}</view>
      </picker>
      <view class="code-row" v-if="captchaEnabled">
        <input v-model="account.code" placeholder="请输入验证码" class="input code-input" maxlength="4" />
        <view class="captcha-img" @click="refreshCaptcha">
          <image :src="captchaUrl" class="captcha-image" mode="aspectFit" />
        </view>
      </view>
      <button class="register-btn" :disabled="loading" @click="registerAccount">注册</button>
    </view>

    <!-- 手机注册表单 -->
    <view v-else class="register-form">
      <input v-model="phone.username" placeholder="请输入用户名(可留空，则使用手机号)" class="input" maxlength="20" />
      <input v-model="phone.nickName" placeholder="请输入昵称" class="input" maxlength="20" />
      <input v-model="phone.phone" placeholder="请输入手机号" class="input" maxlength="11" />
      <view class="code-row">
        <input v-model="phone.code" placeholder="请输入短信验证码" class="input code-input" maxlength="6" />
        <button class="code-btn" :disabled="codeTimer > 0 || loading" @click="sendCode">
          {{ codeTimer > 0 ? codeTimer + 's' : '获取验证码' }}
        </button>
      </view>
      <input v-model="phone.password" placeholder="请设置登录密码（至少6位，含字母数字）" class="input" type="password" maxlength="20" />
      <input v-model="phone.confirmPassword" placeholder="请确认密码" class="input" type="password" maxlength="20" />
      <picker :value="sexIndexPhone" :range="sexOptions" range-key="label" @change="(e)=>onSexChange(e,'phone')" class="picker">
        <view class="picker-text" :class="{ 'placeholder': sexIndexPhone === -1 }">{{ sexLabelPhone }}</view>
      </picker>
      <button class="register-btn" :disabled="loading" @click="registerPhone">注册</button>
    </view>

    <!-- 返回登录 -->
    <view class="back-login">
      <text>已有账号？</text>
      <button class="login-btn" @click="goToLogin">返回登录</button>
    </view>
  </view>
</template>

<script>
import { register as apiRegister, sendSmsCode, getCodeImg } from '@/api/login.js'

export default {
  data() {
    return {
      regType: 'account',
      // 账号注册
      account: {
        username: '',
        password: '',
        confirmPassword: '',
        nickName: '',
        email: '',
        phone: '',
        sex: '',
        code: ''
      },
      // 手机注册
      phone: {
        username: '',
        nickName: '',
        phone: '',
        code: '',
        password: '',
        confirmPassword: '',
        sex: ''
      },
      sexOptions: [
        { label: '男', value: '0' },
        { label: '女', value: '1' },
        { label: '未知', value: '2' }
      ],
      sexIndexAcc: -1,
      sexIndexPhone: -1,
      // 图形验证码
      captchaEnabled: true,
      captchaUrl: '',
      captchaUuid: '',
      // 短信计时
      codeTimer: 0,
      codeInterval: null,
      loading: false
    }
  },
  created() {
    this.getCaptcha()
  },
  methods: {
    // 获取图形验证码
    async getCaptcha() {
      try {
        const data = await getCodeImg()
        if (data && (data.img && data.uuid)) {
          this.captchaUrl = 'data:image/gif;base64,' + data.img
          this.captchaUuid = data.uuid
          this.captchaEnabled = data.captchaEnabled === undefined ? true : !!data.captchaEnabled
        } else {
          this.captchaEnabled = false
        }
      } catch (e) {
        this.captchaEnabled = false
      }
    },
    refreshCaptcha() { this.getCaptcha() },

    // 发送短信验证码
    async sendCode() {
      if (!/^1[3-9]\d{9}$/.test(this.phone.phone)) {
        uni.showToast({ title: '请输入正确手机号', icon: 'none' })
        return
      }
      try {
        const res = await sendSmsCode(this.phone.phone)
        if (res.code === 200) {
          uni.showToast({ title: '验证码已发送', icon: 'success' })
      this.codeTimer = 60
      this.codeInterval = setInterval(() => {
        this.codeTimer--
            if (this.codeTimer <= 0) clearInterval(this.codeInterval)
          }, 1000)
        } else {
          uni.showToast({ title: res.msg || '发送失败', icon: 'none' })
        }
      } catch (e) {
        uni.showToast({ title: '发送失败', icon: 'none' })
      }
    },

    // 性别选择
    onSexChange(e, which) {
      const idx = Number(e.detail.value)
      if (which === 'acc') {
        this.sexIndexAcc = idx
        this.account.sex = this.sexOptions[idx]?.value || ''
      } else {
        this.sexIndexPhone = idx
        this.phone.sex = this.sexOptions[idx]?.value || ''
      }
    },

    // 账号注册
    async registerAccount() {
      if (!this.validateAccount()) return
      this.loading = true
      try {
        const payload = {
          username: this.account.username.trim(),
          password: this.account.password,
          nickName: this.account.nickName.trim(),
          email: this.account.email.trim(),
          phone: this.account.phone.trim(),
          sex: this.account.sex
        }
        if (this.captchaEnabled) {
          payload.code = this.account.code
          payload.uuid = this.captchaUuid
        }
        const res = await apiRegister(payload)
        if (res.code === 200) {
          uni.showToast({ title: '注册成功', icon: 'success' })
          setTimeout(this.goToLogin, 1000)
        } else {
          uni.showToast({ title: res.msg || '注册失败', icon: 'none' })
        }
      } catch (e) {
        uni.showToast({ title: '注册失败', icon: 'none' })
      } finally {
        this.loading = false
      }
    },

    // 手机注册
    async registerPhone() {
      if (!this.validatePhone()) return
      this.loading = true
      try {
        const username = this.phone.username?.trim() || this.phone.phone.trim()
        const payload = {
          username,
          password: this.phone.password,
          nickName: this.phone.nickName.trim(),
          phone: this.phone.phone.trim(),
          sex: this.phone.sex,
          code: this.phone.code // 使用同名字段，后端可兼容短信验证码
        }
        const res = await apiRegister(payload)
        if (res.code === 200) {
          uni.showToast({ title: '注册成功', icon: 'success' })
          setTimeout(this.goToLogin, 1000)
        } else {
          uni.showToast({ title: res.msg || '注册失败', icon: 'none' })
        }
      } catch (e) {
        uni.showToast({ title: '注册失败', icon: 'none' })
      } finally {
        this.loading = false
      }
    },

    // 校验
    validateAccount() {
      if (!this.account.username.trim()) return uni.showToast({ title: '请输入用户名', icon: 'none' }), false
      if (!this.account.password || this.account.password.length < 6 || !/[A-Za-z]/.test(this.account.password) || !/\d/.test(this.account.password))
        return uni.showToast({ title: '密码至少6位且含字母和数字', icon: 'none' }), false
      if (this.account.password !== this.account.confirmPassword) return uni.showToast({ title: '两次密码不一致', icon: 'none' }), false
      if (!this.account.nickName.trim()) return uni.showToast({ title: '请输入昵称', icon: 'none' }), false
      if (this.account.phone && !/^1[3-9]\d{9}$/.test(this.account.phone)) return uni.showToast({ title: '手机号格式不正确', icon: 'none' }), false
      if (this.account.email && !/^[\w-.]+@([\w-]+\.)+[\w-]{2,4}$/.test(this.account.email)) return uni.showToast({ title: '邮箱格式不正确', icon: 'none' }), false
      if (!this.account.sex) return uni.showToast({ title: '请选择性别', icon: 'none' }), false
      if (this.captchaEnabled && !this.account.code) return uni.showToast({ title: '请输入验证码', icon: 'none' }), false
      return true
    },
    validatePhone() {
      if (!/^1[3-9]\d{9}$/.test(this.phone.phone)) return uni.showToast({ title: '请输入正确手机号', icon: 'none' }), false
      if (!this.phone.code || !/^\d{4,6}$/.test(this.phone.code)) return uni.showToast({ title: '请输入短信验证码', icon: 'none' }), false
      if (!this.phone.password || this.phone.password.length < 6 || !/[A-Za-z]/.test(this.phone.password) || !/\d/.test(this.phone.password))
        return uni.showToast({ title: '密码至少6位且含字母和数字', icon: 'none' }), false
      if (this.phone.password !== this.phone.confirmPassword) return uni.showToast({ title: '两次密码不一致', icon: 'none' }), false
      if (!this.phone.nickName.trim()) return uni.showToast({ title: '请输入昵称', icon: 'none' }), false
      if (!this.phone.sex) return uni.showToast({ title: '请选择性别', icon: 'none' }), false
      return true
    },
    goToLogin() {
      uni.navigateBack()
    }
  },
  computed: {
    sexLabelAcc() {
      const opt = this.sexOptions[this.sexIndexAcc]
      return opt ? opt.label : '请选择性别'
    },
    sexLabelPhone() {
      const opt = this.sexOptions[this.sexIndexPhone]
      return opt ? opt.label : '请选择性别'
    }
  },
  onUnload() {
    if (this.codeInterval) clearInterval(this.codeInterval)
  }
}
</script>

<style scoped>
.container {
  min-height: 100vh;
  background: #f5f5f5;
  padding: 40rpx 20rpx 0 20rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.tabs {
  display: flex;
  width: 100%;
  margin-bottom: 30rpx;
  background: #fff;
  border-radius: 15rpx;
  padding: 10rpx;
}
.tab {
  flex: 1;
  text-align: center;
  font-size: 30rpx;
  padding: 20rpx 0;
  color: #999;
  border-radius: 10rpx;
  font-weight: bold;
}
.tab.active { color: #007AFF; background: #f0f8ff; }
.register-form {
  width: 100%;
  background: #fff;
  border-radius: 15rpx;
  padding: 40rpx 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.06);
  display: flex;
  flex-direction: column;
  align-items: center;
}
.input {
  width: 100%;
  padding: 20rpx;
  border: 1px solid #ddd;
  border-radius: 8rpx;
  font-size: 28rpx;
  margin-bottom: 30rpx;
  background: #f8f8f8;
}
.picker {
  width: 100%;
  padding: 20rpx;
  border: 1px solid #ddd;
  border-radius: 8rpx;
  font-size: 28rpx;
  margin-bottom: 30rpx;
  background: #f8f8f8;
}
.code-row {
  display: flex;
  width: 100%;
  margin-bottom: 30rpx;
}
.code-input {
  flex: 2;
  margin-right: 20rpx;
}
.code-btn {
  flex: 1;
  background: #007AFF;
  color: #fff;
  border: none;
  border-radius: 8rpx;
  font-size: 26rpx;
  padding: 20rpx 0;
}
.picker-text{ 
  color:#333; 
}
.picker-text.placeholder {
  color: #999;
}
.captcha-img{ flex:1; height:80rpx; border:1px solid #ddd; border-radius:8rpx; overflow:hidden; }
.captcha-image{ width:100%; height:100%; }
.register-btn {
  width: 100%;
  background: #007AFF;
  color: #fff;
  border: none;
  border-radius: 8rpx;
  font-size: 30rpx;
  padding: 20rpx 0;
  margin-top: 10rpx;
}
.back-login {
  margin-top: 40rpx;
  display: flex;
  align-items: center;
}
.login-btn {
  background: none;
  color: #007AFF;
  border: none;
  font-size: 28rpx;
  margin-left: 10rpx;
  text-decoration: underline;
}
</style>